<script lang='ts' setup>
import { getStore } from '@/assets/工具/工具类';
import { USER } from '@/assets/工具/枚举';
import { doPatch } from '@/assets/工具/网络请求';
import router from '@/router';
import type { FormInstance, FormRules } from 'element-plus';
import { computed, reactive, ref } from 'vue';

const loginErrorMessage = ref('')/* 错误提醒文字 */
const showAlert = ref(false) /* 错误提示是否显示 */
const isLoading = ref(false)  /* 加载中遮罩层 */
const ruleFormRef = ref<FormInstance>()  /* 表单实例对象 */
const formData = reactive({
    originalPass:'',
    password:'',
    checkPass:''
})

/* 
rule:校验规则（可以不传，但是要占位）
value:表单元素的输入值
callback：错误提示语（有参数则提示，没参数则不提示）
*/

const validataPass = (rule:any,value:any,callback:any) =>{
    if(value === ''){  /* 判断确认密码是否为空 */
        callback(new Error('请输入确认密码'))
    }else if( value !== formData.password){  //判断两次密码是否一致
        callback(new Error('两次密码不一致'))
    }else{
        callback()  //清空错误提示
    }
}
const validataPass2 = (rule:any,value:any,callback:any) => {
    if(value === ''){  //判断密码是否为空
        callback(new Error('请输入确认密码'))
    }else if(value !== formData.password){//判断确认密码与新密码是否一致
    callback(new Error('两次密码不一致'))    
    }else{
        callback() //清空错误提示
    }
}

const oldValidataPass = (rule:any,value:any,callback:any) => {
    if(value === ''){  //判断密码是否为空
        callback(new Error('请输入旧密码'))
    }else if(value !== getStore().token.password){//判断旧密码与填入密码是否一致
    callback(new Error('旧密码错误'))    
    }else{
        callback() //清空错误提示
    }
}
const changePassRules = reactive<FormRules<typeof formData>>({
    /* 
    表单验证规则有四种：
    1：非空校验required
    2:elementPlus自带的校验规则（例如max最大长度，min最小长度）
    3：pattern正则表达式。
    4：validator校验函数。
    */

    originalPass:[{validator:oldValidataPass,trigger:'blur'}],
    password:[{validator:validataPass,trigger:'blur'}],
    checkPass:[{validator:validataPass2,trigger:'blur'}]
})

const submitForm = (formEl:FormInstance | undefined) =>{
    if(!formEl)return //判断表单对象是否为空
    formEl.validate((valid) => {  //vaild 为表单验证状态，true则通过，false则未通过
        if(valid){
            /* 
            
            */

            if(formData.originalPass !== getStore().token.password)return


            doPatch(USER.USER_INFO+'/'+ getStore().token.id,{
            password:formData.password
           }).then(res =>{
            if(res.status === 200){
                router.push('/login')
            }else{
                loginErrorMessage.value = '密码修改失败'
                showAlert.value = true
            }
           }).catch(error => {
            
           })
            
        
        }

    })
    setTimeout(() => {
        loginErrorMessage.value=''
        showAlert.value = false
    },3000)
}
const resetForm = (formEl: FormInstance | undefined) => {
    if(!formEl) return 
    formEl.resetFields()
}


</script>
<template>
    <div id="登录页面">
      <div id="登录窗口">
        <el-alert :title="loginErrorMessage" type="error" v-if="showAlert" show-icon center id="错误提示" />
        <h2>修改密码</h2>
        <el-form label-width="80px" id="表单" v-loading="isLoading" :rules="changePassRules" ref="ruleFormRef"
          :model="formData">
          <el-form-item label="原始密码" prop="originalPass">
            <el-input v-model="formData.originalPass" show-password type="password" />
          </el-form-item>
          <el-form-item label="新的密码" prop="password">
            <el-input v-model="formData.password" show-password type="password" />
          </el-form-item>
          <el-form-item label="确认密码" prop="checkPass">
            <el-input v-model="formData.checkPass" show-password type="password" />
          </el-form-item>
          <div id="按钮行">
            <el-button type="info" @click=resetForm>重置</el-button>
            <el-button type="success" @click="submitForm(ruleFormRef)">提交</el-button>
          </div>
        </el-form>
      </div>
    </div>
  </template>
  <style scoped>
  h2 {
    text-align: center;
    margin-bottom: 100px;
  }
  
  #错误提示 {
    width: 300px;
    position: absolute;
    left: calc(50% - 150px);
    top: -50px;
  }
  
  :deep(.slide-verify-slider) {
    margin-top: -5px;
  }
  
  #验证码 {
    position: fixed;
    left: calc(50% - 155px);
    top: 50px;
  }
  
  #按钮行 {
    display: flex;
    justify-content: space-between;
    width: 180px;
    margin: 150px auto;
  }
  
  #表单 {
    width: 300px;
    height: 200px;
    text-align: center;
    margin: auto;
  }
  
  #登录页面 {
    height: 100%;
  }
  
  #登录窗口 {
    width: 500px;
    height: 100%;
    box-sizing: border-box;
    padding-top: 50px;
    margin: auto;
    border: 1px solid #CCC;
    border-bottom: none;
    border-top: none;
  }
  </style>